import request from "../../common/utils/request";
const global = {
  state: {
    departmentMember: [], //部门和成员
    departmentList: [], // 部门列表
    uncheckCount: 0, // 待审核人员数量
    departmentTopKey: 0,
    buildingListInfo: {}, // 当前用户的所有楼宇信息
    leaseTempTags: [], // 退租模板关键词
    printTempTags: {}, // 打印模板关键词
    // 合同审核列表类型
    contractAplTypeList: [],
    // 用户（审核人员列表）
    approvalUserList: [],
    noticePrintTags: [], //缴费通知单打印模板关键词
    tableConfig: {
      size: "small",
      tableContentSize: "12px", // table 内容字号
      tableTitleSize: "14px", // table title 字号
      tableHeaderSize: "14px", // table 表头 字号
      isZebra: true,
      zebraColor: "#fafafa",
      isBordered: true,
    },
  },
  mutations: {
    SET_DEPARTMENT_MEMBER: (state, list) => {
      state.departmentMember = list;
    },
    SET_DEPARTMENT_LIST: (state, list) => {
      if (state.departmentList.length && state.departmentMember.length) {
        // 如果withUser=1的情况下已经获取过了，那么清空使其重新获取到更新的数据
        state.departmentMember = [];
      }
      state.departmentList = list;
    },
    SET_UNCHECK_COUNT: (state, count) => {
      state.uncheckCount = count;
    },
    SET_DEPARTMENT_TOP_KEY: (state, key) => {
      state.departmentTopKey = key;
    },
    SET_BUILDING_LIST_INFO: (state, info) => {
      state.buildingListInfo = { ...state.buildingListInfo, ...info };
    },
    SET_LEASE_TEMP_TAGS: (state, list) => {
      state.leaseTempTags = list;
    },
    SET_PRINT_TEMP_TAGS: (state, { key, list }) => {
      state.printTempTags[key] = list;
    },
    SET_CONTRACT_APL_TYPE_LIST: (state, list) => {
      state.contractAplTypeList = list;
    },
    SET_APPROVAL_USER_LIST: (state, list) => {
      state.approvalUserList = list;
    },
    SET_NOTICE_PRINT_TAGS: (state, list) => {
      state.noticePrintTags = list;
    },
    SET_TABLE_CONFIG: (state, info) => {
      state.tableConfig = { ...info };
    },
  },
  actions: {
    /**
     * @description: 获取部门和成员信息并存储
     * @param {*} withUser =1时返回部门下的成
     * @return {*}
     */
    SetDepartmentMember({ commit }, { withUser = 0 }) {
      return new Promise((resolve, reject) => {
        request
          .get("/org", "/department/index", {
            withUser,
          })
          .then((res) => {
            let list = getApartmentUserList(res.list);
            withUser == 1
              ? commit("SET_DEPARTMENT_MEMBER", list)
              : commit("SET_DEPARTMENT_LIST", list);
            commit("SET_UNCHECK_COUNT", res.hasCheck);
            commit("SET_DEPARTMENT_TOP_KEY", list[0].id);
            resolve(list);
          });
      });
    },
    /**
     * @description: 获取楼宇、集合、项目列表
     */
    GetBuildingListInfo({ state, commit }) {
      return new Promise((resolve) => {
        let result = state.buildingListInfo;
        if (!Object.keys(result).length) {
          const success = (res) => {
            if (res.type == "village") {
              result.buildingList = [];
              result.villageList = res.villageList.map((village) => {
                village.buildIds = [];
                if (village.buildList.length) {
                  village.buildList.forEach((build) => {
                    village.buildIds.push(build.id);
                    result.buildingList.push(build);
                  });
                }
                village.type = "village";
                return village;
              });
            }
            if (res.type == "bucket") {
              result.bucketList = res.list.map((bucket) => {
                bucket.name = bucket.collection_name;
                bucket.buildIds = [];
                if (bucket.collection_build && bucket.collection_build.length) {
                  bucket.collection_build.forEach((build) => {
                    bucket.buildIds.push(build.id);
                  });
                }
                bucket.type = "bucket";
                delete bucket.collection_build;
                return bucket;
              });
            }
            if (Object.keys(result).length == 3) {
              // 保证bucketList和villageList中的buildList引用的同一内存中的build
              const { bucketList, buildingList } = result;
              bucketList.forEach((bucket) => {
                bucket.buildList = [];
                if (bucket.buildIds.length) {
                  bucket.buildIds.forEach((id) => {
                    const build = buildingList.find((item) => item.id == id);
                    bucket.buildList.push(build);
                  });
                }
              });
              commit("SET_BUILDING_LIST_INFO", result);
              resolve(result);
            }
          };
          request
            .get("/org", "/build/villageAndBuildList")
            .then((res) => success({ ...res, type: "village" }));
          request
            .get("/org", "/build/collection")
            .then((res) => success({ ...res, type: "bucket" }));
        } else {
          resolve(result);
        }
      });
    },
    /**
     * @description: 获取退租协议模板关键字
     */
    GetLeaseTempTags({ state, commit }) {
      console.log("GetLeaseTempTagsGetLeaseTempTagsGetLeaseTempTags");
      return new Promise((resolve) => {
        if (state.leaseTempTags.length) {
          resolve(state.leaseTempTags);
        } else {
          request.get("/org", "/contract/retreatTemplateInit").then((res) => {
            const { data } = res;
            let list = [];
            for (let key in data) {
              list.push({
                key,
                title: LEASE_DICT[key],
                list: data[key],
              });
            }
            commit("SET_LEASE_TEMP_TAGS", list);
            resolve(list);
          });
        }
      });
    },
    /**
     * @description: 获取打印模板关键字
     */
    GetPrintTempTags({ state, commit }, { key }) {
      return new Promise((resolve) => {
        if (state.printTempTags[key] && state.printTempTags[key].length) {
          resolve(state.printTempTags[key]);
        } else {
          request.get("/org", "/contract/printTemplateInit").then((res) => {
            const { data } = res;
            let list = [];
            for (let i in data) {
              let dataList = [];
              for (let j in data[i]) {
                dataList.push({
                  key: j,
                  title: PRINT_DICT[j] || PRINT_DICT[`${i}_${j}`],
                  list: data[i][j],
                });
              }
              commit("SET_PRINT_TEMP_TAGS", { key: i, list: dataList });
              if (i == key) {
                list = dataList;
              }
            }
            resolve(list);
          });
        }
      });
    },
    /**
     * @description: 存储合同审批类型列表
     */
    SetContractAplTypeList({ commit }, list) {
      commit("SET_CONTRACT_APL_TYPE_LIST", list);
    },

    /**
     * @description: 存储合同审批类型列表
     */
    GetUserList({ state, commit }, keyword) {
      return new Promise((resolve) => {
        if (state.approvalUserList.length) {
          resolve(state.approvalUserList);
        } else {
          request.get("/org", "/user/getAdminList", { keyword }).then((res) => {
            commit("SET_APPROVAL_USER_LIST", res.list);
            resolve(res.list);
          });
        }
      });
    },
    /**
     * @description: 获取缴费通知单打印模板关键字
     */
    GetNoticePrintTags({ state, commit }) {
      console.log("GetNoticePrintTagsGetNoticePrintTags");
      return new Promise((resolve) => {
        if (state.noticePrintTags.length) {
          resolve(state.noticePrintTags);
        } else {
          request.get("/org", "/notice/characterTemplateInit").then((res) => {
            const { data } = res;
            let list = [];
            for (let key in data) {
              list.push({
                key,
                title: NOTICE_DICT[key],
                list: data[key],
              });
            }
            commit("SET_NOTICE_PRINT_TAGS", list);
            resolve(list);
          });
        }
      });
    },

    /**
     * @description: 在伸缩模式下 table 样式修改
     */
    SetTableConfig({ commit }, data) {
      commit("SET_TABLE_CONFIG", data);
    },
  },
};

const LEASE_DICT = {
  ownerInfo: "租客信息",
  houseInfo: "房源信息",
  settlementPrice: "结算金额",
  detailPrice: "费用明细",
};
const PRINT_DICT = {
  contractInfo: "合同信息",
  houseInfo: "房源信息",
  ownerInfo: "租客信息",
  lateFeeInfo: "滞纳金条款",
  specialField: "自定义字段",
  mainClause: "基本条款",
  bondClause: "保证金条款",
  leaseClause_taxClause: "租金含税",
  propertyClause_taxClause: "物业费含税",
  leaseClause_leaseClause: "租期条款",
  propertyClause_leaseClause: "物业条款",
  // leaseClause: "租期条款",
  specialClause_leaseClause: "租期条款",
  specialClause_taxClause: "自定义费用含税",
  incrClause: "递增率条款",
  discountClause: "优惠",
  specialPriceReport: "租金明细报表",
  contractDetail: "合同明细",
  remarkClause: "备注条款",
  energyInfo: "水电信息",
  propertyInfo: "资产信息",
  payeeInfo: "出租方信息",
};

const NOTICE_DICT = {
  contractInfo: "合同信息",
  contractExtraInfo: "合同拓展字段",
  ownerInfo: "租客信息",
  houseInfo: "房源信息",
  accountInfo: "账户信息",
  otherInfo: "其他信息",
};

/**
 * @description: 转换机构部门角色等数据
 * @param {Array}list
 * @return {Array}
 */
const getApartmentUserList = (list) => {
  return list.map((item) => {
    item.key = item.id;
    item.value = item.id;
    item.title = item.name;
    if (item.subcat && item.subcat.length) {
      item.children = getApartmentUserList(item.subcat);
    } else {
      item.isLeaf = true;
    }
    delete item.subcat;
    return item;
  });
};

export default global;
